package com.epcs.controller.action;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;
import org.apache.tomcat.jni.User;

import com.epcs.model.bo.EmailBO;
import com.epcs.model.bo.ExternalServiceBO;
import com.epcs.model.dao.UserDAO;
import com.epcs.model.dao.googleWrapper.GoogleAPIWrapper;
import com.epcs.model.dao.outlookWrapper.OutlookAPIWrapper;
import com.epcs.model.dto.Account;
import com.epcs.model.dto.Email;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class PermissionAction extends ActionSupport implements SessionAware, ServletRequestAware {

	// -------- Attribute ------//
	private SessionMap<String, Object> sessionMap;
	private HttpServletRequest request;
	// access token for getting refresh token
	private String code;
	private String redirectURL;
	private String email;

	// -------- Method ------//
	// ----- Get permission of external service -----//
	public String getCalendarPermission() {

		String resultString = "NotSupport";

		if (email != null) {
			if (!email.equals("")) {
				// luu email session (để sau này còn lấy ra mà ghi vào DB)
				sessionMap.put("EMAIL", email);

				if (email.endsWith("@gmail.com")) {
					// set type of email
					sessionMap.put("EMAIL_TYPE", "GOOGLE");
					// set redirectURL
					redirectURL = GoogleAPIWrapper.getAuthURL();
					// redirect to permission page of google
					resultString = "Support";

				} else if (email.endsWith("@outlook.com") || email.endsWith("@hotmail.com")
						|| email.endsWith("@live.com")) {
					// set type of email
					sessionMap.put("EMAIL_TYPE", "OUTLOOK");
					// set redirectURL
					redirectURL = OutlookAPIWrapper.getAuthURL();
					// redirect to permission page of outlook
					resultString = "Support";
				} else {
					resultString = "NotSupport";
				}
			}

		}

		return resultString;
	}

	public String savePermission() {
		String resultString = "Fail";
		// get account session
		Account account = (Account) sessionMap.get("USER_INFO");
		// get email session
		String email = (String) sessionMap.get("EMAIL");
		// get type of email session
		String typeOfEmail = (String) sessionMap.get("EMAIL_TYPE");

		try {
			// neu da login
			if (account != null) {
				if (email != null) {
					if (!email.equals("")) {

						String refreshToken = "";
						if (typeOfEmail.equals("GOOGLE")) {
							// get refresh token
							refreshToken = new GoogleAPIWrapper().getRefreshToken(code);
						} else if (typeOfEmail.equals("OUTLOOK")) {
							// get refresh token
							refreshToken = new OutlookAPIWrapper().getRefreshToken(code);
							System.out.println("refreshToken " + refreshToken);
						}

						if (!refreshToken.equals("")) {
							String epcsCalendarID = null;
//							if (typeOfEmail.equals("GOOGLE")) {
//								// tạo 1 calendar tên là EPCS trên server google
//								epcsCalendarID = new ExternalServiceBO()
//										.createEpcsCalendarOnGoogle(refreshToken);
//							} else if (typeOfEmail.equals("OUTLOOK")) {
//								// tạo 1 calendar tên là EPCS trên server google
//								epcsCalendarID = new ExternalServiceBO()
//										.createEpcsCalendarOnOutlook(refreshToken);
//							}

							// create Email object
							Email emailObj = new Email(account, email, refreshToken, epcsCalendarID);

							// insert email to DB
							EmailBO bo = new EmailBO();
							if (bo.insertEmail(emailObj)) {
								resultString = "Success";

								/*
								 * do email có sự thay đổi nhưng email set trong account van chua
								 * đổi do object chưa dc load lại gây khó khăn khi sử dụng
								 * 
								 * --> phải load lại account
								 */

								account = new UserDAO().loadUser(account.getUsername());
								sessionMap.put("USER_INFO", account);

							}
						}
					}
				}
			} else { // neu het session , hoac chua login
				resultString = "Unauthorized";
			}
		} catch (Exception ex) {
			resultString = "Fail";
			request.setAttribute("ERROR_TYPE", "getPermissionError");
		}
		return resultString;
	}

	// -------- Getter Setter ------//
	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getRedirectURL() {
		return redirectURL;
	}

	public void setRedirectURL(String redirectURL) {
		this.redirectURL = redirectURL;
	}

	// -------- Session ------//
	@Override
	public void setSession(Map<String, Object> sessionMap) {
		this.sessionMap = (SessionMap<String, Object>) sessionMap;

//		System.out.println("get sessionMap in permission");
//		System.out.println("session = " + sessionMap);
//		System.out.println("session map = " + sessionMap.toString());
//		System.out.println("session context = " + ActionContext.getContext().getSession().toString());
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;

	}
}
